<script setup lang="ts">
import { updateProfileAPI } from '@/apis/updateProfile'
import { uploadFileAPI } from '@/apis/uploadFile'
import { useUserInfoStore } from '@/store/userInfo'
import avatarPlaceholder from '@/static/images/avatar_placeholder.png'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 表单数据
const formData = ref({
  avatar: userInfoStore.userInfo?.avatar || '',
  mobile: userInfoStore.userInfo?.mobile || '',
  username: userInfoStore.userInfo?.nickname || '',
})

// 校验规则
const rules = {
  avatar: [
    { required: true, message: '头像不可为空', trigger: ['blur', 'change'] },
  ],
  mobile: [
    { required: true, message: '手机号不可为空', trigger: ['blur', 'change'] },
  ],
  username: [
    { required: true, message: '姓名不可为空', trigger: ['blur', 'change'] },
  ],
}

// 表单组件ref
const formRef = ref<any>(null)
// 是否处于加载中状态
const loading = ref(false)

const handleChooseAvatar = useThrottleFn(async () => {
  uni.chooseFile({
    count: 1,
    type: 'image',
    complete: (result) => {
      (result.tempFiles as File[]).forEach(async (file) => {
        const res = await uploadFileAPI({
          tempFilePath: (file as any).path,
          fileType: 'image',
        }, userInfoStore.userInfo!.token!)
        if (res.data) {
          const resData = JSON.parse(res.data)
          formData.value.avatar = resData.data.fullurl
        }
      })
    },
  })
}, 1000)

/**
 * @description 提交表单时触发
 */
const handleSubmit = useThrottleFn(() => {
  if (userInfoStore.userInfo && userInfoStore.userInfo.token) {
    formRef.value.validate()
      .then(async () => {
        // 控制加载状态
        loading.value = true
        try {
          const res = await updateProfileAPI(
            formData.value,
            userInfoStore.userInfo!.token,
          )
          if (res.data?.code === 1) {
            userInfoStore.setUserInfo({
              ...userInfoStore.userInfo!,
              nickname: formData.value.username,
              mobile: formData.value.mobile,
              avatar: formData.value.avatar,
            })
            uni.showModal({
              title: '提交成功',
              showCancel: false,
              success: () => router.back(),
            })
          }
          else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
        }
        catch (err) {
          uni.showToast({ title: '提交失败，请重试', icon: 'none' })
        }
      })
      .catch((errors: AnyObject[]) => {
        // 表单验证失败
        if (errors.length > 0)
          uni.showToast({ title: errors[0].message, icon: 'none' })
      })
  }
  else {
    uni.showToast({ title: '提交失败，请重试', icon: 'none' })
  }
})
</script>

<template>
  <Spacer h="40" />
  <view class="px-24rpx">
    <view class="overflow-hidden rounded-10rpx bg-white">
      <uv-form ref="formRef" :model="formData" :rules="rules" class="rounded-10rpx bg-white">
        <ListCell label="姓名">
          <input v-model="formData.username" class="h-126rpx rounded-10rpx bg-white text-right text-32rpx text-#333333 leading-45rpx" value="" placeholder="请输入您的姓名">
        </ListCell>
        <Divider color="#F0F0F0" />
        <ListCell label="手机号">
          <input v-model="formData.mobile" type="number" class="h-126rpx rounded-10rpx bg-white text-right text-32rpx text-#333333 leading-45rpx" value="" placeholder="请输入您的手机号">
        </ListCell>
        <Divider color="#F0F0F0" />
        <button
          :style="{ padding: 0, margin: 0, background: 'none' }"
          @tap="handleChooseAvatar"
        >
          <ListCell label="头像">
            <image class="my-20rpx h-80rpx w-80rpx rounded-full" :src="formData.avatar || avatarPlaceholder" />
          </ListCell>
        </button>
        <button class="fixed bottom-40rpx h-120rpx w-690rpx flex items-center justify-center rounded-10rpx bg-#3F8BF6 text-36rpx text-white font-bold leading-50rpx x-center" hover-class="bg-#2070E0" @tap="handleSubmit">
          确认修改
        </button>
      </uv-form>
    </view>
  </view>
</template>

<route lang="yaml">
name: 'profileSettings'
style:
  navigationBarTitleText: '个人信息'
</route>
